import pyglet

import cocos
from cocos.layer import ColorLayer
from cocos.actions import *
from cocos.director import director
from random import random
from math import floor

from gamelib import music

sx, sy = 1024, 768

class Cutscene(ColorLayer):
    def __init__(self, a, b, c, d):
        super(Cutscene, self).__init__(a, b, c, d)
        self.timer = 0.01
        self.textspeed = 0.05 # seconds per character
        self.fname = "Times New Roman"
    def addcaption(self, words):
        cap = cocos.text.Label(words, font_name = self.fname,
          font_size = 22, anchor_x = "center")
        cap.position = sx/2, sy-50
        t = 0.3 + self.textspeed * len(words)
        cap.do(Hide() + Delay(self.timer) + Show() +
          FadeIn(0.4) + Delay(t) + FadeOut(0.4))
        self.add(cap)
        self.timer += t + 0.8
    def addtalk(self, who, words):
        if hasattr(words, "__iter__"):
            wlist = words
            wlist.reverse()
        else:
            wlist = [words]
        t = 0.1
        for w in wlist:
          t += self.textspeed * len(w)
        x, y = who.position
        y += 64
        for w in wlist:
            say = cocos.text.Label(w, font_name = self.fname,
              font_size = 16, anchor_x = "center")
            say.position = x, y
            y += 22
            say.do(Hide() + Delay(self.timer) + Show() +
              FadeIn(0.1) + Delay(t) + FadeOut(0.1))
            self.add(say)
        self.timer += t + 0.2
    def addwalk(self, who, whither):
        dt = abs(whither) * 0.005
        for w in who:
            nsteps = int(abs(whither) / 40. * (1 + random()/3.))
            stepsize = whither * 0.5 / nsteps
            steplen = abs(stepsize * 0.005)
            walkthisway = MoveBy((stepsize, 10), steplen) + MoveBy((stepsize, -10), steplen)
            w.do(Delay(self.timer) + walkthisway * nsteps)
        self.timer += dt
    def appear(self, what):
        what.do(Delay(self.timer) + Show())
    def disappear(self, what):
        what.do(Delay(self.timer) + Hide())
    def addaction(self, action, t):
        self.do(Delay(self.timer) + action)
        self.timer += t

    def add_done(self):
        self.do(Delay(self.timer) + CallFunc(self.do_done))
    def do_done(self):
        director.pop()

    def on_enter(self):
        super(Cutscene, self).on_enter()

        self.music_player = music.play('music_story_mp.ogg')

    def on_exit(self):
        super(Cutscene, self).on_exit()

        self.music_player.pause()
        self.music_player = None

def Intro(female = False):
    i = Cutscene(64, 64, 64, 255)

    SnipEffect = Blink(times = 4, duration = .25) + Show()

    i.addcaption("Once upon a time, in the realm of the Fates...")
    i.addcaption("where a mortal's destiny is decided...")
    i.addcaption("by the length of a piece of thread....")


    fate = [cocos.sprite.Sprite("fate-y.png"),
      cocos.sprite.Sprite("fate-m.png"),
      cocos.sprite.Sprite("fate-o.png"), ]
    for j in range(0, 3):
        fate[j].position = sx/2 + (j-1) * 100, sy/2
        i.add(fate[j])
    item = cocos.sprite.Sprite("spinning-wheel.png")
    item.position = sx/2 - 110, sy/2# - 30
    i.add(item, z=1)
    scissors = cocos.sprite.Sprite("scissors.png")
    scissors.position = sx/2 + 100, sy/2 - 30
    i.add(scissors, z=1)

    i.addtalk(fate[0], "...spin...")
    i.addtalk(fate[1], "...measure...")
    i.addtalk(fate[2], "...cut...")
    i.addtalk(fate[1], "This one will be a farmer.")

    i.addtalk(fate[0], "...spin...")
    i.addtalk(fate[1], "...measure...")
    i.addtalk(fate[2], "...cut...")
    i.addtalk(fate[1], "This one will be a king.")

    i.addtalk(fate[0], "...spin...")
    i.addtalk(fate[1], "...measure...")
    i.addtalk(fate[2], "...cut...")
    i.addtalk(fate[1], "And this poor, pathetic, unloved fool...")
    i.addtalk(fate[1], "...he'll be a game maker!!!")

    i.addtalk(fate[1], "Hehehehehehehehehehehehehehe!!!!")
    i.addtalk(fate[0], "I love this job.")
    nobody = cocos.sprite.Sprite("fate-o.png")
    nobody.position = sx-120, sy/2
    nobody.do(Hide())
    i.addtalk(nobody, "Free beer!")
    i.addtalk(nobody, "Free beer for goddesses!")
    i.addtalk(fate[2], "What?!")
    i.addtalk(fate[1], "Who said that?!")
    #i.addtalk(fate[0], "Beer? Yucky!")
    #i.addtalk(nobody, "Uh, did I say beer?")
    #i.addtalk(nobody, ["I meant, uh, girly...", "...sewing...stuff..."])
    #i.addtalk(nobody, "and Hello Kitty toys!")
    #i.addtalk(fate[2], "Hello Kitty!!!")
    #i.addtalk(fate[1], "EEEEEEEEEEEEEEEEEEEEEE!!!!!")
    i.addwalk(fate, sx/2 + 200)


    baddy = cocos.sprite.Sprite("big-bad.png")
    baddy.position = sx/2 + 150, sy/2 + 20
    i.add(baddy)
    i.addwalk([baddy], sx/2 + 250)
    i.addtalk(baddy, "Yoink!")
    baddy.position = -100, sy/2 + 20

    i.disappear(scissors)
    i.addwalk([baddy], -(sx/2 + 350))
    i.addwalk(fate, -(sx/2 + 200))
    i.addtalk(fate[1], "                          ")
    i.addtalk(fate[1], "Ah, crud.")

    i.disappear(fate[0])
    i.disappear(fate[1])
    i.disappear(fate[2])
    i.disappear(item)
    i.addcaption("But few are worthy to wield the power of the Fates.")

    victim1 = cocos.sprite.Sprite("person-m-brown.png")
    victim1.position = sx/2, sy/2
    victim1.do(ScaleBy(2))
    victim1.do(Hide())
    i.add(victim1)
    i.appear(victim1)
    i.addtalk(victim1, "Ah, I love being a candy-maker!")
    i.addcaption("SNIP!")
    i.addaction(SnipEffect, 1)
    i.addtalk(victim1, "It's pretty good being a baker!")
    i.addcaption("SNIP!")
    i.addaction(SnipEffect, 1)
    i.addtalk(victim1, "Selling soup.... it's a living!")
    i.addcaption("SNIP!")
    i.addaction(SnipEffect, 1)
    i.addtalk(victim1, "Sigh.... another day as a fishmonger.")
    i.addcaption("SNIP!")
    i.addaction(SnipEffect, 1)
    i.addtalk(victim1, "Someone please buy something from a poor sprout-seller!")
    i.disappear(victim1)

    i.addcaption("And though the lives of mortals are trivial to some,")
    i.addcaption("the mortals themselves take them very, very seriously.")

    himg, limg = "person-m-brown.png", "person-f-green.png"
    if female: himg, limg = limg, himg

    hero = cocos.sprite.Sprite(himg)
    hero.position = sx/2 + 50, sy/2
    hero.do(ScaleBy(2))
    love = cocos.sprite.Sprite(limg)
    love.position = sx/2 - 50, sy/2
    love.do(ScaleBy(2))
    i.add(hero)
    i.add(love)
    hero.do(MoveBy((sx/2 + 150, 0), 0))
    love.do(MoveBy((sx/2 + 150, 0), 0))
    i.addwalk([hero, love], -(sx/2 + 150))
    i.addwalk([love], -100)
    i.addtalk(love, "               ")
    i.addwalk([love], 100)
    i.addtalk(love, "What's wrong, my love?")
    i.addtalk(hero, ["I'll soon be old",  "enough to go to war."])
    i.addtalk(love, ["You know I won't", "let that happen!"])
    i.addtalk(love, ["For I'll soon be old", "enough to fulfill my destiny..."])
    i.addtalk(love, "and rule this land!")
    i.addtalk(love, "And I will end this war!")
    i.addtalk(hero, ["The fate of so many of", "us rests in your hands,", "my dear!"])
    i.addcaption("SNIP!")
    i.addaction(SnipEffect, 1)
    i.addtalk(hero, "Did you see that?!")
    i.addtalk(love, ["I... I'm sorry, I", "seem to be lost."])
    i.addtalk(hero, "Lost? You're with me!")
    i.addtalk(love, "I beg your pardon....")
    i.addtalk(love, ["I am a humble wine", "bearer, servant to", "the drunken Duke,"])
    i.addtalk(love, ["who will surely punish", "me harshly if I", "don't return!"])
    i.addtalk(love, ["Forgive me.", "I do not know you,"])
    i.addtalk(love, ["but something about", "you makes me feel", "as though I do...."])
    i.addwalk([love], -150)
    i.addtalk(love, "                  ")
    i.addwalk([love], 200)
    i.addtalk(love, "*KISS*")
    i.addwalk([love], -sx/2 - 200)
    hero.do(Delay(i.timer) + MoveBy((-(sx/2+200), 0), 0))


    pub = cocos.text.Label("TAVERN", font_name = "Times New Roman",
        font_size = 20, anchor_x = "center")
    pub.position = sx/2, sy-100
    pub.do(Hide())
    i.add(pub)
    i.appear(pub)
    bartender = cocos.sprite.Sprite("person-m-blue.png")
    bartender.position = sx/2+160, sy/2
    bartender.do(ScaleBy(2.5))
    bartender.do(Hide())
    i.add(bartender)
    i.appear(bartender)
    i.addwalk([hero], sx/2+200)
    i.addtalk(bartender, "What'll it be, kid?")
    i.addtalk(hero, ["What's good for when", "your life's been", "turned upside down"])
    i.addtalk(hero, ["and you're going to be", "drafted into the army,", "because the love of",
      "your life's memory has", "been erased,"])
    i.addtalk(hero, ["accompanied by a", "preternatural flashing",
      "and an ineffable sense", "that things are not", "as they should be?"])
    i.addtalk(bartender, "Ah geez, you too?")
    i.addtalk(hero, ["What do you mean,", "me too?"])
    i.addtalk(bartender, ["That's the fourth time", "I've heard that today!"])
    i.addtalk(hero, "What? Who else?")
    i.addtalk(bartender, "Right over there.")
    i.disappear(bartender)
    i.disappear(pub)
    hero.do(Delay(i.timer) + MoveBy((sx/2-100, 0), 0))

    party = [cocos.sprite.Sprite("person-f-purple.png"),
      cocos.sprite.Sprite("person-m-blue.png"),
      cocos.sprite.Sprite(limg)]
    for j in range(0, 3):
        party[j].position = sx/2 + (j-3) * 80, sy/2
        party[j].do(ScaleBy(2))
        party[j].do(Hide())
        i.add(party[j])
        i.appear(party[j])
    i.addwalk([hero], -(sx/2-100))
    i.addtalk(hero, "Hail and well met!")
    i.addtalk(hero, ["I heard you might", "know something about..."])
    i.addtalk(hero, "...fate?")
    i.addtalk(party[0], ["I might know something,", "young one."])
    i.addtalk(party[0], ["I used to work for", "a wise and well-", "informed warlock,"])
    i.addtalk(party[0], ["before he woke up this", "morning believing himself",
      "to be a gutter cleaner."])
    i.addtalk(party[0], ["I heard him say that", "the power of the Fates",
      "themselves has been", "taken, who knows", "for what purpose."])
    i.addtalk(hero, ["Well what are we", "waiting for?! Let's", "get it back!"])
    i.addtalk(party[1], "Yeah, we could do that.")
    i.addtalk(party[1], ["Or, we could", "just get drunk."])
    i.addtalk(party[2], "It's not easy, friend.")
    i.addtalk(party[2], ["Five strands of the", "Threads of Fate must",
      "be collected to", "restore those lives", "now stolen."])
    i.addtalk(party[1], ["Have you ever fought", "a god before? No?", "I didn't think so.",
      "So just forget about it."])
    i.addtalk(hero, ["That's not good", "enough for me! I'm", "going and nothing", "can stop me!"])
    i.addwalk([hero], -(sx/2+200))
    i.addtalk(party[2], "Wait for me!")
    i.addwalk([party[2]], -(sx/2+120))
    i.addtalk(party[0], ["Eh, why not? I'm out", "of a job anyway."])
    i.addwalk([party[0]], -(sx/2))
    i.addtalk(party[1], "......")
    i.addtalk(party[1], "               ")
    i.addtalk(party[1], "Dammit....")
    i.addwalk([party[1]], -(sx/2))

    i.addcaption("You must retrieve the strands and restore your beloved's fate!")
    i.addcaption("For your beloved's sake, for your sake, and for the sake of the world!")
    i.add_done()

    return i


def Finish1():
    f = CutScene(0, 0, 0, 255)
    f.addcaption("Congratulations!")
    f.addcaption("You defeated the minion and retrieved a strand!")

    f.add_done()
    return f

